package logic

import (
	"context"
	"strings"
	"time"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateMenuLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateMenuLogic {
	return &BackendCreateMenuLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendCreateMenuLogic) BackendCreateMenu(in *backend.CreateMenuRequest) (*backend.CreateMenuResponse, error) {
	if len(strings.TrimSpace(in.Name)) == 0 {
		return nil, errorx.Status(errorx.ERROR_MENU_NAME_REQUIRED, "")
	}

	_, count, err := l.svcCtx.BackendMenu.GetList(l.ctx, model.M{
		model.BackendMenuColumns.Name: in.Name,
	}, 0)
	if err != nil {
		return nil, err
	}
	if count > 0 {
		return nil, errorx.Status(errorx.ERROR_MENU_NAME_EXISTS, "")
	}

	var menu model.BackendMenu
	menu.Name = in.Name
	menu.ParentID = uint64(in.Pid)
	menu.Icon = in.Icon
	menu.Path = in.Path
	menu.API = in.Api
	menu.URL = in.Url
	menu.Type = uint8(in.Type)
	menu.Status = uint8(in.Status)
	menu.DelStatus = uint8(in.Status)
	menu.MenuOrder = uint(in.MenuOrder)
	menu.CreatedBy = uint64(in.CreatedBy)
	menu.LastUpdatedBy = uint64(in.CreatedBy)
	menu.CreatedAt = time.Now()
	menu.UpdatedAt = time.Now()

	err = l.svcCtx.BackendMenu.Insert(l.ctx, &menu)
	if err != nil {
		return nil, err
	}

	return &backend.CreateMenuResponse{}, nil
}
